<?php
/**
 * Created by PhpStorm.
 * User: Woo
 * Date: 2018/3/19
 * Time: 14:46
 */

namespace App\Services;


use App\Task\EasyChatTask;
use Hhxsv5\LaravelS\Swoole\Task\Task;
use Hhxsv5\LaravelS\Swoole\WebsocketHandlerInterface;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class WebsocketService implements WebsocketHandlerInterface
{
    public function __construct()
    {
    }

    public function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
    {

        Redis::lpush('fds',$request->fd);
//        $server->push($request->fd, 'Welcome Here And Chat Secretly.');
        $user_num = Redis::llen('fds');
        switch ($user_num){
            case 1 :
                $note = '广漠的黑域中，下一个进来的会是谁？';break;
            default:
                $note = '在这未知的角落，'.--$user_num.'位好奇的客人正等着你';
        }
        $server->push($request->fd, $note);
        $fds = Redis::lrange('fds',0,-1);
        foreach($fds as $fd){
            if($fd <> $request->fd){
                $server->push($fd, '用户：'.$request->fd.'加入');
            }
        }
        // throw new \Exception('an exception'); //上层会自动忽略handle时抛出的异常
    }
    public function onMessage(\swoole_websocket_server $server, \swoole_websocket_frame $frame)
    {
        $data = [
            'fd'=>$frame->fd,
            'string'=>'用户'.$frame->fd.'说：'.$frame->data
        ];
        Task::deliver(new EasyChatTask($data));
    }

    public function onClose(\swoole_websocket_server $server, $fd, $reactorId)
    {
        $fds = Redis::lrange('fds', 0, -1);
        if(!in_array($fd,$fds)){
            return;
        }
        Redis::lrem('fds', 1, $fd);
        $data = [
            'fd'=>$fd,
            'string'=>'用户'.$fd.'离开'
        ];
        Task::deliver(new EasyChatTask($data));
    }
}